import axios, { AxiosRequestConfig } from 'axios';
import router from '@/router';

const instance = axios.create({
  timeout: 30 * 1000,
});

instance.interceptors.request.use(config => {
  const token = localStorage.getItem('user_token');
  if (token) {
    config.headers.Authorization = `${token}`;
  }
  return config;
});

instance.interceptors.response.use(
  response => {
    const { code, message: msg } = response.data || {}
    if (code != 'ok') {
      message.error(msg);
      if (code == 'UN_LOGIN') {
        router.push({ path: '/login' });
      }
      if (code == 'NO_PERMISSION') {
        // NO_PERMISSION - 您没有资源的操作权限
      }
      return response.data
    }
    return response.data;
  },
  err => {
    if (err.response?.status === 401) {
      router.push({ path: '/login' });
    } else if (err.message) {
      message.error(err.message);
    }
    return Promise.reject(err);
  }
);

export type Response<T = any> = {
  code: string;
  data: T;
  message: string;
};

type Request = <T>(
  url: string,
  params?: Obj,
  config?: AxiosRequestConfig
) => Promise<Response<T>>;

export const get: Request = (url, params = {}, config = {}) => {
  return instance({
    url,
    method: 'get',
    params,
    ...config,
  });
};

export const post: Request = (url, params = {}, config = {}) => {
  return instance({
    url,
    method: 'post',
    data: params,
    ...config,
  });
};

export const put: Request = (url, params = {}, config = {}) => {
  return instance({
    url,
    method: 'put',
    data: params,
    ...config,
  });
};

export const del: Request = (url, params = {}, config = {}) => {
  return instance({
    url,
    method: 'delete',
    params,
    ...config,
  });
};
